package com.samuel.blog.service.impl;

import com.samuel.blog.dao.RoleDao;
import com.samuel.blog.entity.RoleEntity;
import com.samuel.blog.service.RoleService;
import com.samuel.blog.utils.RedisUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kaiji
 */
@Service("roleService")
@Transactional
public class RoleServiceImpl extends BaseServiceImpl<RoleEntity, String> implements RoleService {

	@Resource(name = "roleDao")
	private RoleDao roleDao;
	
	@Resource(name = "redisUtil")
	private RedisUtil redisUtil;
	
	@Override
    public RoleEntity selectByName(String name) {
		RoleEntity roleEntity = null;
		boolean exists = redisUtil.exists(name);
		if (exists) {
			roleEntity = redisUtil.get(name, RoleEntity.class);
		} else {
			HashMap<String, Object> map = new HashMap<>();
			map.put("name", name);
			List<RoleEntity> selectByMap = roleDao.selectByMap(map);
			if (null != selectByMap && selectByMap.size() > 0) {
				roleEntity = selectByMap.get(0); 
			}
		}
		return roleEntity;
	}

	@Override
	public int saveRoleJur(String roleId, String[] ids) {
		// 删除 roleId 拥有的权限
		roleDao.deleteRoleJur(roleId);
		
		try {
			for (String jurisdictionId : ids) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("roleId", roleId);
				map.put("jurisdictionId", jurisdictionId);
				map.put("createDate", new Date());
				roleDao.saveRoleJur(map);
			}
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	@Override
	public RoleEntity selectByAuthorId(String authorId) {
		return roleDao.selectByAuthorId(authorId);
	}

	@Override
	public int deleteBatch(String[] ids) {
		try {
			for (String roleId : ids) {
				roleDao.deleteByPrimaryKey(roleId);
				roleDao.deleteRoleJur(roleId);
			}
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

}
